<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\adminapi\controller\goods;

use app\adminapi\controller\Base;
use app\service\goods\ContentService;

class Content extends Base
{
    /**
     * Get goods paid content - all types: text, multi_chapter, chapter_groups, file, multi_file
     */
    public function getPaidContent()
    {
        $id = inputs("id/d", 0);
        if (!$id) {
            $this->error(trans('goods_id_required'));
        }

        $contentService = new ContentService();
        // Backend gets paid content without specific content, only basic info (id, title, resource type)
        $contentData = $contentService->getGoodsPaidContent($id, true, 0, false);

        $this->success('', $contentData);
    }

    /**
     * Update goods paid content - text type, file type, multi_file type
     */
    public function updateContent()
    {
        $id           = inputs("id/d", 0);
        $paid_content = inputs("paid_content/s", "");

        if (!$id) {
            $this->error(trans('goods_id_required'));
        }

        $contentService = new ContentService();
        $result         = $contentService->updateGoodsPaidContent($id, $paid_content);

        if ($result) {
            $this->success();
        } else {
            $this->error(trans('operation_successful'));
        }
    }

    /**
     * Update goods single file content
     */
    public function updateFileContent()
    {
        $id          = inputs("id/d", 0);
        $title       = inputs("title/s", "");
        $description = inputs("description/s", "");
        $file_url    = inputs("file_url/s", "");
        $file_size   = inputs("file_size/d", 0);

        if (!$id) {
            $this->error(trans('goods_id_required'));
        }

        if (empty($title)) {
            $this->error(trans('file_title_required'));
        }

        if (empty($file_url)) {
            $this->error(trans('file_url_required'));
        }

        $fileData = [
            'title'       => $title,
            'description' => $description,
            'file_url'    => $file_url,
            'file_size'   => $file_size,
        ];

        $contentService = new ContentService();
        $result         = $contentService->updateGoodsFileContent($id, $fileData);

        if ($result) {
            $this->success();
        } else {
            $this->error(trans('operation_successful'));
        }
    }

    /**
     * Update goods multi-file content
     */
    public function updateMultiFileContent()
    {
        $id       = inputs("id/d", 0);
        $action   = inputs("action/s", "add"); // add, update, delete
        $fileData = [];

        // Get file data based on different operations
        if ($action == 'add' || $action == 'update') {
            // Get file data from frontend
            $fileData = request()->post('file', []);
            if (empty($fileData)) {
                $this->error(trans('file_data_required'));
            }
        }

        if (!$id) {
            $this->error(trans('goods_id_required'));
        }

        // Add or update file
        if ($action == 'add' || $action == 'update') {
            // Validate required fields
            if (empty($fileData['title'])) {
                $this->error(trans('file_title_required'));
            }

            if (empty($fileData['file_url'])) {
                $this->error(trans('file_url_required'));
            }
        }

        // Validate file ID (for required operations)
        $fileId = 0;
        if (($action == 'update' || $action == 'delete')) {
            $fileId = inputs("file_id/d", 0);
            if (!$fileId) {
                $this->error(trans('file_id_required'));
            }
        }

        $contentService = new ContentService();
        $result         = false;

        try {
            switch ($action) {
                case 'add':
                    // Add single file
                    $result = $contentService->addMultiFileItem($id, $fileData);
                    break;
                case 'update':
                    // Update single file
                    $result = $contentService->updateMultiFileItem($id, $fileId, $fileData);
                    break;
                case 'delete':
                    // Delete single file
                    $result = $contentService->deleteMultiFileItem($id, $fileId);
                    break;
                default:
                    throw new \Exception(trans('unknown_operation_type'));
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        if ($result) {
            $this->success();
        } else {
            $this->error();
        }
    }

    /**
     * Get complete information of a single chapter (for editing)
     */
    public function getChapterDetail()
    {
        $id       = inputs("id/d", 0);
        $goods_id = inputs("goods_id/d", 0);

        if (empty($id)) {
            $this->error(trans('chapter_id_required'));
        }

        if (empty($goods_id)) {
            $this->error(trans('goods_id_required'));
        }

        $contentService = new ContentService();
        $chapter        = $contentService->getChapterDetail($id, $goods_id);

        if ($chapter) {
            $this->success('', $chapter);
        } else {
            $this->error(trans('chapter_not_exists'));
        }
    }

    /**
     * Save single chapter
     */
    public function saveChapter()
    {
        $data = [
            'id'             => inputs("id/d", 0), // Chapter ID, 0 means new
            'goods_id'       => inputs("goods_id/d", 0),
            'group_id'       => inputs("group_id/d", 0),
            'title'          => inputs("title/s", ""),
            'content'        => inputs("content/s", ""),
            'sort'           => inputs("sort/d", 0),
            'is_free'        => inputs("is_free/d", 0),
            'resource_type'  => inputs("resource_type/s", "text"),
            'video_url'      => inputs("video_url/s", ""),
            'video_duration' => inputs("video_duration/d", 0),
            'audio_url'      => inputs("audio_url/s", ""),
            'audio_duration' => inputs("audio_duration/d", 0),
            'cloud_url'      => inputs("cloud_url/s", ""),
            'cloud_password' => inputs("cloud_password/s", ""),
        ];

        if (empty($data['goods_id'])) {
            $this->error(trans('goods_id_required'));
        }

        if (empty($data['title'])) {
            $this->error(trans('chapter_title_required'));
        }

        // Validate required fields based on resource type
        $this->validateResourceFields($data);

        $contentService = new ContentService();

        if ($data['id'] > 0) {
            // Update existing chapter
            $chapter = $contentService->updateChapter($data['id'], $data);
        } else {
            // Add new chapter
            unset($data['id']); // Remove ID field
            $chapter = $contentService->addChapter($data);
        }

        $this->success('', $chapter);
    }

    /**
     * Delete single chapter
     */
    public function deleteChapter()
    {
        $id       = inputs("id/d", 0);
        $goods_id = inputs("goods_id/d", 0);

        if (empty($id)) {
            $this->error(trans('chapter_id_required'));
        }

        if (empty($goods_id)) {
            $this->error(trans('goods_id_required'));
        }

        $contentService = new ContentService();
        $result         = $contentService->deleteChapter($id, $goods_id);

        if ($result) {
            $this->success();
        } else {
            $this->error();
        }
    }

    /**
     * Validate resource fields
     */
    private function validateResourceFields($data)
    {
        $resourceType = $data['resource_type'] ?? 'text';

        switch ($resourceType) {
            case 'video':
                if (empty($data['video_url'])) {
                    $this->error(trans('video_url_required'));
                }
                break;
            case 'audio':
                if (empty($data['audio_url'])) {
                    $this->error(trans('audio_url_required'));
                }
                break;
            case 'cloud':
                if (empty($data['cloud_url'])) {
                    $this->error(trans('cloud_url_required'));
                }
                break;
            case 'longtext':
                if (empty($data['content'])) {
                    $this->error(trans('longtext_content_required'));
                }
                // Long text will be saved to file, no additional validation needed
                break;
            case 'text':
            default:
                // Text type uses existing logic, no additional validation needed
                break;
        }
    }
}